package com.crazymaker.cloud.disruptor.demo.starter;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.Environment;

import java.net.*;
import java.util.Enumeration;
import java.util.List;


@Slf4j
@SpringBootApplication(scanBasePackages =
        {
                "com.crazymaker.cloud.disruptor",
        }
)


public class DisruptorProviderApplication {
    public static void main(String[] args) {
        ConfigurableApplicationContext applicationContext = SpringApplication.run(DisruptorProviderApplication.class, args);

        Environment env = applicationContext.getEnvironment();
        String port = env.getProperty("server.port");
        String name = env.getProperty("spring.application.name");

        String path = env.getProperty("server.servlet.context-path");
        if (StringUtils.isBlank(path)) {
            path = "";
        }
        String ip =getLocalIP();

        System.out.println("\n----------------------------------------------------------\n\t" +
                name.toUpperCase() + " is running! Access URLs:\n\t" +
                "Local: \t\thttp://" + ip + ":" + port + path + "/\n\t" +
                "swagger-ui: \thttp://" + ip + ":" + port + path + "/swagger-ui.html\n\t" +
                "actuator: \thttp://" + ip + ":" + port + path + "/actuator/info\n\t" +
                "----------------------------------------------------------");
    }

    /**
     * 获取本机ip
     *
     * 通过 获取系统所有的networkInterface网络接口 然后遍历 每个网络下的InterfaceAddress组。
     * 获得符合 <code>InetAddress instanceof Inet4Address</code> 条件的一个IpV4地址
     * @return
     */
    public static String getLocalIP(){
        String ip = null;
        Enumeration allNetInterfaces ; //java.util中的一个接口类，在Enumeration中封装了有关枚举数据集合的方法
        try {
            allNetInterfaces = NetworkInterface.getNetworkInterfaces();  //得到本机所有的网络接口并存入Enumeration中
            while (allNetInterfaces.hasMoreElements()) { //遍历判断Enumeration 中是否含有元素
                NetworkInterface networkInterface = (NetworkInterface) allNetInterfaces.nextElement(); //取出该元素
                List<InterfaceAddress> interfaceAddresses = networkInterface.getInterfaceAddresses(); //获取此网络接口的全部或部分 InterfaceAddresses 所组成的列表
                for (InterfaceAddress address : interfaceAddresses) {
                    InetAddress inetAddress = address.getAddress(); //得到byte数组形式的IP地址
                    if (inetAddress != null && inetAddress instanceof Inet4Address) {
                        ip = inetAddress.getHostAddress(); //获取本机的IP地址
                    }
                }
            }
        } catch (SocketException e) {
            System.err.println("获取本机ip发生异常： "+e);
        }
        return ip;
    }
}